<template>
  <view class="page">
    <!-- 顶部使用系统导航栏；页面内部不再渲染自定义标题与浮动返回 -->
    <view class="notice">待支付，剩余时间：{{ countdownText }}</view>

    <view class="card user">
      <image class="avatar" :src="'/static/project/2025-10-14_110352_756.png'" />
      <view class="meta">
        <text class="name">{{ coachName || '陪爬服务' }}</text>
        <text class="desc">需要陪爬服务</text>
      </view>
    </view>

    <view class="card service">
      <text class="section">服务详情</text>
      <view class="svc">
        <image class="svc-img" src="/static/project/2025-10-14_110352_756.png" mode="aspectFill" />
        <view class="svc-meta">
          <text class="svc-title">{{ serviceTitle }}</text>
          <text class="svc-sub">{{ durationText }}</text>
        </view>
      </view>
      <view class="row" v-if="placeText"><text class="icon">📍</text><text class="text">{{ placeText }}</text></view>
      <view class="row"><text class="icon">🗓</text><text class="text">{{ dateTimeText }}</text></view>
    </view>

    <view class="card fee">
      <view class="row between"><text>订单金额</text><text>¥{{ Number(totalAmount).toFixed(2) }}</text></view>
    </view>

    <view class="card paytype">
      <text class="section">选择支付方式</text>
      <view class="pt-item" :class="{active: payType==='points'}" @tap="payType='points'">
        <view class="pay-option">
          <text class="pay-name">积分支付</text>
          <text class="pay-desc">当前积分：{{ userPoints }}</text>
        </view>
        <radio :checked="payType==='points'"/>
      </view>
    </view>

    <view class="footer">
      <button class="btn" :class="{ disabled: userPoints < pointsRequired }" @tap="submitPay">
        立即支付 {{ pointsRequired }} 积分
      </button>
    </view>
  </view>
</template>

<script>
import { getOrder, payOrder, payOrderWithPoints, cancelOrder } from '@/api/order'
import { getUserPoints } from '@/api/system/user'
export default {
  data(){
    return {
      id: '',
      coachName: '',
      serviceTitle: '陪爬预约服务',
      durationText: '',
      placeText: '',
      dateTimeText: '',
      serviceAmount: 0,
      totalAmount: 0,
      payType: 'points',
      userPoints: 0,
      expireAt: 0,
      nowTimer: 0,
      cancelTimeout: 0,
      isFinalized: false, // 已完成（支付或取消）
      countdownSeconds: 0,
      orderNo: ''
    }
  },
  computed: {
    countdownText(){
      const sec = Math.max(0, Number(this.countdownSeconds) || 0)
      const m = String(Math.floor(sec/60)).padStart(2,'0')
      const s = String(sec%60).padStart(2,'0')
      return `${m}:${s}`
    },
    // 计算需要多少积分（1元=1积分）
    pointsRequired() {
      return Math.ceil(this.totalAmount)
    }
  },
  onLoad(q){
    this.id = q && q.id
    this.fetch()
    this.loadUserPoints()
    // 每秒刷新倒计时并在超时后自动取消
    this.nowTimer = setInterval(()=>{
      if (!this.expireAt) return
      const remain = Math.max(0, Math.floor((this.expireAt - Date.now()) / 1000))
      this.countdownSeconds = remain
      if (remain <= 0) {
        clearInterval(this.nowTimer); this.nowTimer = 0
        if (!this.isFinalized) this.autoCancel()
      }
    }, 1000)
  },
  onUnload(){
    clearInterval(this.nowTimer)
    if (this.cancelTimeout) clearTimeout(this.cancelTimeout)
  },
  onNavigationBarButtonTap() {
    // 部分端支持自定义导航栏按钮事件，这里兜底返回
    this.handleBack()
  },
  methods: {
    handleBack(){
      // 优先返回上一页；无历史栈则重定向到订单列表（tab页路径为 /pages/order/list）
      const pages = getCurrentPages && getCurrentPages()
      if (pages && pages.length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({ url: '/pages/order/list' })
      }
    },
    async fetch(){
      if (!this.id) return
      const res = await getOrder(this.id)
      const o = res.data || res
      this.serviceAmount = Number(o.amount || 0)
      this.totalAmount = this.serviceAmount
      this.durationText = `${o.startTime || ''}-${o.endTime || ''}`
      this.dateTimeText = `${o.serviceDate || ''} ${this.durationText}`
      this.coachName = o.coachName || ''
      this.orderNo = o.orderNo || ''
      // 标题与地点均来自路线规划（如果有）
      const plan = o.routePlan || ''
      this.serviceTitle = plan || this.serviceTitle
      this.placeText = plan
      // 5分钟支付时限（进入页面开始计时）
      this.expireAt = Date.now() + 5*60*1000
      this.countdownSeconds = Math.ceil((this.expireAt - Date.now())/1000)
      // 到时自动取消
      if (this.cancelTimeout) clearTimeout(this.cancelTimeout)
      this.cancelTimeout = setTimeout(this.autoCancel, 5*60*1000)
    },
    async autoCancel(){
      if (this.isFinalized) return
      try{
        const r = await cancelOrder(this.id, '超时未支付自动取消')
        this.isFinalized = true
        uni.showToast({ title: '已自动取消', icon: 'none' })
        setTimeout(()=>{ uni.switchTab({ url: '/pages/order/list' }) }, 600)
      }catch(e){
        // 即使取消失败也返回列表
        this.isFinalized = true
        uni.switchTab({ url: '/pages/order/list' })
      }
    },
    // 加载用户积分
    async loadUserPoints() {
      try {
        const response = await getUserPoints()
        this.userPoints = response.points || 0
      } catch (error) {
        this.userPoints = 0
      }
    },
    async submitPay(){
      try {
        // 检查积分是否足够
        if (this.userPoints < this.pointsRequired) {
          uni.showModal({
            title: '积分不足',
            content: `当前积分：${this.userPoints}，需要积分：${this.pointsRequired}。积分不够请找管理员充值`,
            showCancel: false,
            confirmText: '知道了'
          })
          return
        }

        uni.showLoading({ title: '支付中...' })
        
        // 调用积分支付接口（后端自动根据订单金额计算积分）
        const response = await payOrderWithPoints(this.id)
        
        uni.hideLoading()
        
        if (response.code === 200) {
          uni.showToast({ title: '支付成功', icon: 'success' })
          // 重新加载用户积分
          this.loadUserPoints()
          this.isFinalized = true
          if (this.cancelTimeout) clearTimeout(this.cancelTimeout)
          // 支付成功提示并引导出示订单号
          uni.showModal({
            title: '温馨提示',
            content: `请到游客大厅出示订单号：${this.orderNo || '—'}`,
            showCancel: false,
            success: () => {
              uni.reLaunch({ url: '/pages/order/list' })
            }
          })
        } else {
          uni.showToast({ title: response.msg || '支付失败', icon: 'none' })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('支付失败:', error)
        uni.showToast({ title: '支付失败，请重试', icon: 'none' })
      }
    }
  }
}
</script>

<style scoped>
.page { padding: 0 12rpx 160rpx 12rpx; background:#f7fafc; }
/* 顶部自定义导航，固定在顶部并适配安全区 */
.nav { 
  position: sticky; 
  top: 0; 
  z-index: 10; 
  display:flex; 
  align-items:center; 
  justify-content: space-between; 
  height: 88rpx; 
  padding-top: constant(safe-area-inset-top); /* iOS < 11.2 */
  padding-top: env(safe-area-inset-top);
  background:#fff; 
  border-bottom: 1rpx solid #eef2f5;
}
.nav-back { width: 88rpx; text-align:center; font-size: 48rpx; line-height: 88rpx; }
.nav-title { flex:1; text-align:center; font-weight:700; }
.nav-right { width: 88rpx; }
.floating-back {
  position: fixed;
  left: 12rpx;
  /* 避开顶部倒计时提示区域，向下偏移 */
  top: calc(env(safe-area-inset-top) + 120rpx);
  z-index: 20;
  width: 64rpx; height: 64rpx;
  line-height: 64rpx; text-align: center;
  border-radius: 32rpx; font-size: 40rpx; font-weight: 600;
  color: #111; background: rgba(255,255,255,.9);
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,.08);
}
.notice { background:#fef9c3; color:#92400e; padding: 12rpx; border-radius: 12rpx; margin-bottom: 12rpx; }
.card { background:#fff; border-radius: 16rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.06); padding: 16rpx; margin-bottom: 12rpx; }
.user { display:flex; align-items:center; }
.avatar { width: 72rpx; height: 72rpx; border-radius: 50%; background:#f3f4f6; }
.meta { margin-left: 12rpx; }
.name { font-weight: 700; }
.service .section, .paytype .section { font-weight: 700; margin-bottom: 8rpx; display:block; }
.svc { display:flex; gap: 12rpx; }
.svc-img { width: 120rpx; height: 90rpx; border-radius: 8rpx; background:#f3f4f6; }
.svc-title { font-weight: 700; }
.svc-sub { color:#6b7280; font-size: 22rpx; }
.row { margin-top: 8rpx; color:#374151; display:flex; align-items:center; }
.row .icon { margin-right: 6rpx; }
.fee .row { padding: 6rpx 0; }
.between { display:flex; align-items:center; justify-content: space-between; }
.total { border-top: 1rpx solid #eef2f5; margin-top: 6rpx; padding-top: 10rpx; }
.sum { color:#ef4444; font-weight: 700; }
.pt-item { display:flex; align-items:center; justify-content: space-between; background:#f8fafc; border-radius: 12rpx; padding: 12rpx; margin-top: 10rpx; }
.pt-item.active { border: 2rpx solid #0ea5a5; background:#ecfeff; }
.pay-option { display: flex; flex-direction: column; }
.pay-name { font-weight: 600; font-size: 28rpx; }
.pay-desc { color: #6b7280; font-size: 24rpx; margin-top: 4rpx; }
.footer { position: fixed; left:0; right:0; bottom:0; padding: 12rpx; background:#fff; box-shadow: 0 -8rpx 24rpx rgba(0,0,0,.06); }
.btn { width: 100%; background:#0ea5a5; color:#fff; border:none; }
.btn.disabled { background:#d1d5db; color:#9ca3af; }
</style>


